package com.fancon.rage.comic;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fancon.rage.comic.dao.RagePhotoDao;
import com.fancon.rage.comic.entity.Photo;
import com.google.appengine.api.datastore.EntityNotFoundException;
/**
 * Base servlet for upload to GAE
 * @author binhbt
 *
 */
@SuppressWarnings("serial")
public abstract class AbstractUploadServlet extends HttpServlet {
    protected RagePhotoDao dao = new RagePhotoDao(); 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	resp.setHeader("Content-Encoding", "utf-8");
    	String action = req.getParameter("action");
        if ("display".equals(action)) {           
            long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?            
            showRecord(id, req, resp);
        } else if("thumb".equals(action)){
            long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?            
            showThumb(id, req, resp);
        }else if("delete".equals(action)){
            long id = Long.parseLong(req.getParameter("id").replace("_", "")); // WTF?            
            delete(id, req, resp);
        }else{
            showForm(req, resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleSubmit(req, resp);
    }

    protected abstract void showForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException;

    protected abstract void handleSubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException;
    protected abstract void delete(long id, HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException;
    
    
    protected void showRecord(long id, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    	Photo photo = null;
		try {
			photo = dao.get(id);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        resp.setContentType(photo.getContentType());        
        resp.getOutputStream().write(photo.getPhotoData());
        resp.flushBuffer();                    
    }

	protected void showThumb(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	Photo photo = null;
		try {
			photo = dao.get(id);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        resp.setContentType(photo.getContentType());        
        resp.getOutputStream().write(photo.getThumbData());
        resp.flushBuffer();  
	}

}
